package com.platform.web.lisenter;

import com.alibaba.fastjson.JSONObject;
import com.platform.base.domain.BaseLocation;
import com.platform.base.domain.UnitValveInfo;
import com.platform.base.service.IBaseLocationService;
import com.platform.base.service.IUnitValveInfoService;
import com.platform.common.manager.AsyncManager;
import com.platform.common.utils.DateUtils;
import com.platform.common.utils.netty.NettyUtil;
import com.platform.common.utils.redis.RedisUtil;
import com.platform.common.utils.spring.SpringUtils;
import com.platform.data.domain.MeterRead;
import com.platform.data.domain.RuleAlarm;
import com.platform.data.domain.UnitValveData;
import com.platform.data.service.IMeterReadService;
import com.platform.data.service.IRuleAlarmService;
import com.platform.data.service.IUnitValveDataService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.TimerTask;

@Component
@Slf4j
public class UnitValveListener {

    @Autowired
    private RedisUtil redisUtil;

    @RabbitListener(queues = "unitValve_queue")
    @RabbitHandler
    public void receiveUnitValve(JSONObject object, Channel channel, Message message){
        try{
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            String messageId = message.getMessageProperties().getHeaders().get("spring_returned_message_correlation").toString();
            if(redisUtil.hasKey("message:"+messageId)){
                return;
            }
            redisUtil.set("message:"+messageId, messageId, 1000);
            //执行异步保存数据
            log.info("执行异步保存阀门数据："+ object.getString("datas"));
            AsyncManager.me().execute(UnitValvePoolTask.saveUnitValve(object.getString("datas"), object.getDate("createTime")));
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}

/**
 * 异步任务保存阀门数据
 */
@Slf4j
class UnitValvePoolTask {


    public static TimerTask saveUnitValve(final String datas, final Date createTime) {
        IUnitValveDataService unitValveDataService = SpringUtils.getBean(IUnitValveDataService.class);
        IUnitValveInfoService unitValveInfoService = SpringUtils.getBean(IUnitValveInfoService.class);
        IBaseLocationService baseLocationService = SpringUtils.getBean(IBaseLocationService.class);
        IRuleAlarmService ruleAlarmService =SpringUtils.getBean(IRuleAlarmService.class);
        log.info("阀门数据=========="+datas);

        return new TimerTask() {
            @Override
            public void run() {
                String[] contents = datas.split(" ");
                //阀id
                String valveId = String.valueOf(NettyUtil.get10HexNum(contents[0]));
                UnitValveInfo info = unitValveInfoService.selectUnitValveInfoById(valveId);
                BaseLocation baseLocation = baseLocationService.selectBaseLocationById(String.valueOf(info.getLocationId()));
                DecimalFormat format = new DecimalFormat("0.000");

                try {
                    //阀温度上限
                  /*  String max = NettyUtil.get10HexNum(contents[3]) + "." + NettyUtil.get10HexNum(contents[4]);
                    //阀温度下限
                    String min = NettyUtil.get10HexNum(contents[5]) + "." + NettyUtil.get10HexNum(contents[6]);
                    //阀温度值
                    String temp = NettyUtil.get10HexNum(contents[7]) * 0.5 + "";
                    //室内温度
                    String indoor = NettyUtil.get10HexNum(contents[10]) + "." + NettyUtil.get10HexNum(contents[9]);
                    //工作时间
                    String work = NettyUtil.get10HexNum(contents[13] + contents[14] + contents[15]) + "";
                    //阀开度
                    String open = NettyUtil.get10HexNum(contents[34]) + "";
                    //错误码
                    int error = NettyUtil.get10HexNum(contents[33]);*/

                    //错误码
                    int error = NettyUtil.get10HexNum(contents[4]);
                    //当前阀门开度
                    String open = format.format(Float.parseFloat(String.valueOf((NettyUtil.get10HexNum(contents[5])*256+NettyUtil.get10HexNum(contents[6])))) * 0.1);
                    //设置阀门开度
                    String saperture = format.format(Float.parseFloat(String.valueOf((NettyUtil.get10HexNum(contents[7])*256+NettyUtil.get10HexNum(contents[8])))) * 0.1) ;
                    //当前温度值
                    String temp = format.format(Float.parseFloat(String.valueOf((NettyUtil.get10HexNum(contents[9])*256+NettyUtil.get10HexNum(contents[10])))) * 0.1) ;
                    //pid功能是否开启
                    String work = NettyUtil.get10HexNum(contents[12])+ "";
                    //设置温度
                    String pidSetv = format.format(Float.parseFloat(String.valueOf((NettyUtil.get10HexNum(contents[13])*256+NettyUtil.get10HexNum(contents[14])))) * 0.1) ;
                    //pidKp
                    String pidKp = format.format(Float.parseFloat(String.valueOf((NettyUtil.get10HexNum(contents[15])*256+NettyUtil.get10HexNum(contents[16])))) * 0.01) ;
                    //pidKi
                    String pidKi = format.format(Float.parseFloat(String.valueOf((NettyUtil.get10HexNum(contents[17])*256+NettyUtil.get10HexNum(contents[18])))) * 0.01) ;
                    //pidKd
                    String pidKd = format.format(Float.parseFloat(String.valueOf((NettyUtil.get10HexNum(contents[19])*256+NettyUtil.get10HexNum(contents[20])))) * 0.01) ;
                    //pidKt
                    String pidKt = (NettyUtil.get10HexNum(contents[21])*256+NettyUtil.get10HexNum(contents[22])) + "";
                    //pidDead
                    String pidDead = format.format(Float.parseFloat(String.valueOf((NettyUtil.get10HexNum(contents[23])*256+NettyUtil.get10HexNum(contents[24])))) * 0.1) ;
                    //pid参数是否远程修改
                    String pidAct = NettyUtil.get10HexNum(contents[26])+ "";
                    //pid参数是否远程修改
                    String pidS = NettyUtil.get10HexNum(contents[28])+ "";

                    UnitValveData unitValveData = new UnitValveData();
                    unitValveData.setValveId(valveId);
                    unitValveData.setWork(work);
                    unitValveData.setSaperture(saperture);
                    unitValveData.setPidAct(pidAct);
                    unitValveData.setPidDead(pidDead);
                    unitValveData.setPidKd(pidKd);
                    unitValveData.setPidKi(pidKi);
                    unitValveData.setPidKp(pidKp);
                    unitValveData.setPidKt(pidKt);
                    unitValveData.setPidS(pidS);
                    unitValveData.setPidSetv(pidSetv);
                    unitValveData.setTemp(temp);
                    unitValveData.setAperture(open);
                    if(createTime==null) {
                        unitValveData.setCreateTime(DateUtils.getNowDate());
                    }else{
                        unitValveData.setCreateTime(createTime);
                    }
                    if(error==170){
                        unitValveData.setStatus("正在向开方向运转");
                    }else if(error==187){
                        unitValveData.setStatus("正在向关方向运转");
                    }else if(error==172){
                        unitValveData.setStatus("开方向运转完成并到位");
                    }else if(error==188){
                        unitValveData.setStatus("关方向运转完成并到位");
                    }else if(error==0){
                        unitValveData.setStatus("系统上电处于刹车状态");
                    }else if(error==234){
                        unitValveData.setStatus("故障报警");
                    }else {unitValveData.setStatus("故障报警");}

                    unitValveDataService.insertUnitValveData(unitValveData);

                }catch (Exception e){
                    e.printStackTrace();

                    AsyncManager.me().execute(AlarmPoolTask.saveAlarm(valveId,String.valueOf(info.getLocationId()), "1", "3", "采集阀门数据", "阀门"+valveId+"数据["+datas+"]有误，解析错误"+e.getMessage()));
                }
            }
        };
    }
}
